package com.aiyige.page.my.merchandisemanagement;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.aiyige.R;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.base.BaseActivity;
import com.aiyige.base.api.ApiManager;
import com.aiyige.base.api.ResponseCode;
import com.aiyige.base.api.apiengine.ModuleEngine;
import com.aiyige.base.db.dao.LearnVideoModelDao;
import com.aiyige.base.db.dao.MajorCourseDBModelDao;
import com.aiyige.base.db.table.LearnVideoModel;
import com.aiyige.base.db.table.MajorCourseDBModel;
import com.aiyige.base.db.table.TraingClassDBModel;
import com.aiyige.base.eventbus.EventDeleteSearchMoment;
import com.aiyige.base.eventbus.EventServerChangeMomentStatus;
import com.aiyige.model.Summary;
import com.aiyige.model.moment.backup.TagBackup;
import com.aiyige.model.moment.entity.Moment;
import com.aiyige.page.my.merchandisemanagement.adapter.MMSearchResultAdapter;
import com.aiyige.page.my.merchandisemanagement.model.SearchResultItem;
import com.aiyige.page.my.merchandisemanagement.model.TabItem;
import com.aiyige.page.publish.selectinterest.model.PublishInterestItem;
import com.aiyige.page.publish.util.PublishUtil;
import com.aiyige.utils.ErrorUtil;
import com.aiyige.utils.HighLightWordUtil;
import com.aiyige.utils.ListUtil;
import com.aiyige.utils.RetrofitUtil;
import com.aiyige.utils.SearchHandlerWrapper;
import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.entity.MultiItemEntity;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.LinkedList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.ResponseBody;
import retrofit2.Response;
import timber.log.Timber;

@Route(path = ARouterConfig.MMSearchGroupPage)
public class MMSearchGroupPage extends BaseActivity implements SearchHandlerWrapper.SearchCallback {
    public static final String TAG = MMSearchGroupPage.class.getSimpleName();
    public static final int HANDLE_SEARCH = 1;
    @BindView(R.id.inputEt)
    EditText inputEt;
    @BindView(R.id.inputEtClearBtn)
    ImageView inputEtClearBtn;
    @BindView(R.id.searchResultRv)
    RecyclerView searchResultRv;
    @Autowired
    String keyword = "";
    SearchHandlerWrapper searchHandlerWrapper;
    Handler mainHandler;
    MMSearchResultAdapter mmSearchResultAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.page_mmsearch_group);
        ButterKnife.bind(this);
        ARouter.getInstance().inject(this);
        setAutoRegisterEventBus(true);
        mmSearchResultAdapter = new MMSearchResultAdapter(this);
        searchResultRv.setLayoutManager(new LinearLayoutManager(this));
        mmSearchResultAdapter.bindToRecyclerView(searchResultRv);
        mmSearchResultAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()) {
                    case R.id.moreLayout:
                        SearchResultItem searchResultItem = mmSearchResultAdapter.getItem(position);
                        ARouter.getInstance()
                                .build(ARouterConfig.MMSearchMorePage)
                                .withInt("type", searchResultItem.getItemType())
                                .withString("keyword", inputEt.getText().toString())
                                .navigation();
                        break;
                }
            }
        });
        mainHandler = new Handler(Looper.getMainLooper());
        searchHandlerWrapper = new SearchHandlerWrapper(TAG + "SearchThread");
        searchHandlerWrapper.setSearchCallback(this);
        inputEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                inputEtClearBtn.setVisibility(s.length() == 0 ? View.INVISIBLE : View.VISIBLE);
                keyword = s.toString().trim();
            }
        });
        inputEt.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    searchHandlerWrapper.postSearch(keyword);
                    return true;
                }
                return false;
            }
        });
        inputEt.setText(keyword);
        searchHandlerWrapper.postSearch(keyword);
    }


    @OnClick({R.id.inputEtClearBtn, R.id.cancelLayout})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.inputEtClearBtn:
                inputEt.setText("");
                break;
            case R.id.cancelLayout:
                finish();
                break;
        }
    }

    @Override
    protected void onDestroy() {
        searchHandlerWrapper.destroy();
        super.onDestroy();
    }

    @Override
    public void search(String searchStr) {
        final List<SearchResultItem> searchResultItemList = new LinkedList<>();
        SearchResultItem learnVideoSearchResultItem = SearchResultItem.newBuilder()
                .itemType(PublishUtil.PARENT_TYPE_LEARN_VIDEO)
                .learnVideoModelList(new LinkedList<LearnVideoModel>())
                .build();
        SearchResultItem majorCourseSearchResultItem = SearchResultItem.newBuilder()
                .itemType(PublishUtil.PARENT_TYPE_MAJOR_COURESE)
                .majorCourseDBModelList(new LinkedList<MajorCourseDBModel>())
                .build();
//        SearchResultItem traingClassSearchResultItem = SearchResultItem.newBuilder()
//                .itemType(TabItem.TAB_ID_TRAING_CLASS)
//                .traingClassDBModelList(new LinkedList<TraingClassDBModel>())
//                .build();
//        SearchResultItem traingCardSearchResultItem = SearchResultItem.newBuilder()
//                .itemType(TabItem.TAB_ID_TRAING_CARD)
//                .traingCardDBModelList(new LinkedList<TraingCardDBModel>())
//                .build();

//        SearchResultItem traingCardSearchResultItem = SearchResultItem.newBuilder()
//                .itemType(TabItem.TAB_ID_TRAING_CARD)
//                .build();
//        SearchResultItem personalTrainerSearchResultItem = SearchResultItem.newBuilder()
//                .itemType(TabItem.TAB_ID_PERSONAL_TRAINER)
//                .build();
//        SearchResultItem universalProductSearchResultItem = SearchResultItem.newBuilder()
//                .itemType(TabItem.TAB_ID_UNIVERSAL_PRODUCT)
//                .build();
        searchResultItemList.add(learnVideoSearchResultItem);
        searchResultItemList.add(majorCourseSearchResultItem);
//        searchResultItemList.add(traingClassSearchResultItem);
//        searchResultItemList.add(traingCardSearchResultItem);
//        searchResultItemList.add(personalTrainerSearchResultItem);
//        searchResultItemList.add(universalProductSearchResultItem);
        if (!TextUtils.isEmpty(searchStr)) {
            try {
                Response<ResponseBody> response = ApiManager.getService()
                        .seachMomentSummary(ModuleEngine.COMMODITY_MANAGER, searchStr, 1)
                        .execute();
                if (response.code() != ResponseCode.OK) {
                    throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                }
                String json = RetrofitUtil.getResponseBodyAsString(response);
                Summary summary = JSON.parseObject(json, Summary.class);
                learnVideoSearchResultItem.setTotalLearnVideo(summary.getVideoCourseCount());
                majorCourseSearchResultItem.setTotalMajorCourse(summary.getMajorCourseCount());
//                traingClassSearchResultItem.setTotalTraingClass(summary.getTrainingCourseCount());
//                traingCardSearchResultItem.setTotalTraingCard(summary.getTraingCardCount());
                if (!ListUtil.isEmpty(summary.getVideoCourse())) {
                    for (Moment item : summary.getVideoCourse()) {
                        Moment moment = new Moment(item);
                        LearnVideoModel learnVideoModel = LearnVideoModel.parse(moment);
                        learnVideoModel.setTitle(HighLightWordUtil.highLight(moment.getTitle(), keyword));
                        learnVideoSearchResultItem.getLearnVideoModelList().add(learnVideoModel);
                    }
                }
                if (!ListUtil.isEmpty(summary.getMajorCourse())) {
                    for (Moment item : summary.getMajorCourse()) {
                        Moment moment = new Moment(item);
                        MajorCourseDBModel majorCourseDBModel = MajorCourseDBModel.parse(moment);
                        majorCourseDBModel.setTitle(HighLightWordUtil.highLight(moment.getTitle(), keyword));
                        majorCourseSearchResultItem.getMajorCourseDBModelList().add(majorCourseDBModel);
                    }
                }

//                for (Moment moment : summary.getTrainingCourse()) {
//                    TraingClassDBModel traingClassDBModel = TraingClassDBModel.parse(moment);
//                    traingClassDBModel.setTitle(HighLightWordUtil.highLight(moment.getTitle(), keyword));
//                    traingClassSearchResultItem.getTraingClassDBModelList().add(traingClassDBModel);
//                }
//                for (Moment moment : summary.getTrainingCard()) {
//                    TraingCardDBModel traingCardDBModel = TraingCardDBModel.parse(moment);
//                    traingCardDBModel.setTitle(HighLightWordUtil.highLight(moment.getTitle(), keyword));
//                    traingCardSearchResultItem.getTraingCardDBModelList().add(traingCardDBModel);
//                }
            } catch (Exception e) {
                Timber.e("handleMessage:" + Log.getStackTraceString(e));
            }
        }
        mainHandler.post(new Runnable() {
            @Override
            public void run() {
                mmSearchResultAdapter.setNewData(searchResultItemList);
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(EventDeleteSearchMoment event) {
        if (!TextUtils.isEmpty(event.getServerId())) {
            switch (event.getParentType()) {
                case PublishUtil.PARENT_TYPE_MAJOR_COURESE: {
                    for (SearchResultItem searchResultItem : mmSearchResultAdapter.getData()) {
                        if (searchResultItem.getItemType() == PublishUtil.PARENT_TYPE_MAJOR_COURESE) {
                            searchResultItem.setTotalMajorCourse(Math.max(0, searchResultItem.getTotalMajorCourse() - 1));
                            int upLimit = searchResultItem.getMajorCourseDBModelList().size();
                            for (int i = 0; i < upLimit; ++i) {
                                if (event.getServerId().equals(PublishUtil.extractServerIdFromMultiItemEntity(searchResultItem.getMajorCourseDBModelList().get(i)))) {
                                    searchResultItem.getMajorCourseDBModelList().remove(i);
                                    break;
                                }
                            }
                            mmSearchResultAdapter.notifyDataSetChanged();
                            break;
                        }
                    }
                    break;
                }
                case PublishUtil.PARENT_TYPE_LEARN_VIDEO: {
                    for (SearchResultItem searchResultItem : mmSearchResultAdapter.getData()) {
                        if (searchResultItem.getItemType() == PublishUtil.PARENT_TYPE_LEARN_VIDEO) {
                            searchResultItem.setTotalLearnVideo(Math.max(0, searchResultItem.getTotalLearnVideo() - 1));
                            int upLimit = searchResultItem.getLearnVideoModelList().size();
                            for (int i = 0; i < upLimit; ++i) {
                                if (event.getServerId().equals(PublishUtil.extractServerIdFromMultiItemEntity(searchResultItem.getLearnVideoModelList().get(i)))) {
                                    searchResultItem.getLearnVideoModelList().remove(i);
                                    break;
                                }
                            }
                            mmSearchResultAdapter.notifyDataSetChanged();
                            break;
                        }
                    }
                    break;
                }
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(EventServerChangeMomentStatus event) {
        if (TextUtils.isEmpty(event.getMomentId())) return;
        int progressStatus;
        switch (event.getTargetStatus()) {
            case Moment.STATUS_IN_REVIEW:
                progressStatus = PublishUtil.PROGRESS_STATUS_IN_REVIEW;
                break;
            case Moment.STATUS_REJECT:
                progressStatus = PublishUtil.PROGRESS_STATUS_REJECT;
                break;
            case Moment.STATUS_PUT_ON:
                progressStatus = PublishUtil.PROGRESS_STATUS_PUBLISHED;
                break;
            case Moment.STATUS_SAVE:
                progressStatus = PublishUtil.PROGRESS_STATUS_NOT_PUBLISHED;
                break;
            case Moment.STATUS_REVIEW_PASSED:
                progressStatus = PublishUtil.PROGRESS_STATUS_PUBLISHED;
                break;
            case Moment.STATUS_GET_OFF:
                progressStatus = PublishUtil.PROGRESS_STATUS_NOT_PUBLISHED;
                break;
            case Moment.STATUS_TRANSCODING:
                progressStatus = PublishUtil.PROGRESS_STATUS_SERVER_TRANSCODING;
                break;
            default:
                progressStatus = PublishUtil.PROGRESS_STATUS_NOT_PUBLISHED;
                break;
        }
        switch (event.getSubject()) {
            case Moment.SUBJECT_MAJOR_COURSE: {
                for (SearchResultItem searchResultItem : mmSearchResultAdapter.getData()) {
                    if (searchResultItem.getItemType() == PublishUtil.PARENT_TYPE_MAJOR_COURESE) {
                        for (MajorCourseDBModel model : searchResultItem.getMajorCourseDBModelList()) {
                            if (event.getMomentId().equals(model.getGoodsId())) {
                                model.setProgressStatus(progressStatus);
                                model.setRejectReason(event.getMessage());
                                try {
                                    MajorCourseDBModelDao.getDao().update(model);
                                } catch (Exception e) {

                                }
                                mmSearchResultAdapter.notifyDataSetChanged();
                                break;
                            }
                        }
                        break;
                    }
                }
                break;
            }
            case Moment.SUBJECT_VIDEO_COURSE: {
                for (SearchResultItem searchResultItem : mmSearchResultAdapter.getData()) {
                    if (searchResultItem.getItemType() == PublishUtil.PARENT_TYPE_LEARN_VIDEO) {
                        for (LearnVideoModel model : searchResultItem.getLearnVideoModelList()) {
                            if (event.getMomentId().equals(model.getGoodsId())) {
                                model.setProgressStatus(progressStatus);
                                model.setRejectReason(event.getMessage());
                                try {
                                    LearnVideoModelDao.getDao().update(model);
                                } catch (Exception e) {

                                }
                                mmSearchResultAdapter.notifyDataSetChanged();
                                break;
                            }
                        }
                        break;
                    }
                }
                break;
            }
        }
    }
}
